import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
} from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { HttpServcie } from "../../../service/http.service";
import { ContractBean } from "./../bean/contract.bean";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import { Observable } from "rxjs/Rx";
import { Config } from "./../../../service/config";

@Component({
  selector: "contract-add-page",
  templateUrl: "contract-add.html",
  styleUrls: ["contract-add.scss"]
})
export class ContractAddPage implements OnInit {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  functions: any = [];
  expandDataCache = {};
  config = Config;
  @Input() inValue: any = [];
  data = [];
  @Output("outPut") outPut = new EventEmitter();
  //合同管理信息
  contractBean: ContractBean = new ContractBean();
  //角色添加的权限(功能)
  funList: any = [];

  //机构的集合
  partyList: any = [];
  //合同类型
  levatorType: any = [];
  userObject: any;
  firstDisable: boolean = false;
  secondDisable: boolean = false;
  //甲方
  firstList: any = [];
  //乙方
  secondList: any = [];
  parentId : string;
  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService
  ) {
    //查询合同类型
    this.querylevatorType();
  }

  /**
   * 选择checkbox
   * @param event
   * @param param
   */
  refreshStatus(event, param) {
    if (event) {
      this.funList.push(param);
    } else {
      //如果非选中状态移除
      if (this.funList.length > 0) {
        this.httpServcie.removeByValue(this.funList, param);
      }
    }
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      firstParty: [null, [Validators.required]],
      secondParty: [null, [Validators.required]],
      contractType: [null, [Validators.required]],
    });
    //获取登陆人信息
    let user: string = window.localStorage.getItem("user");
    if (user) {
      this.userObject = JSON.parse(user);
      this.parentId = this.userObject.partyParentId;
    }
    //甲方
    this.queryByIdAndType(this.userObject["partyParentId"], "2");
    //乙方
    this.queryByIdAndType(this.userObject["partyParentId"], "1");

    this.contractBean.partyId = this.userObject.partyId;
  }

  //查询合同类型
  querylevatorType() {
    this.httpServcie.queryelevatorTypeList().subscribe(data => {
      if (data.status == 200) {
        this.levatorType = data.data.list;
      }
    });
  }

  // 查询甲乙方名称
  queryByIdAndType(partyId, partyType) {
    let param = {
      partyType: partyType,
      id : this.parentId,
    };
    this.httpServcie.queryByIdAndTypeList(param).subscribe(data => {
      if (data.status == 200) {
        if (partyType == "2") {
          this.firstList = data.data;

          if (this.firstList.length > 0 && this.userObject.partyType == "2") {
            this.contractBean.firstParty = this.userObject.partyId;
            this.firstDisable = true;
          }
        } else if (partyType == "1") {
          this.secondList = data.data;
          if (this.secondList.length > 0 && this.userObject.partyType == "1") {
            this.contractBean.secondParty = this.userObject.partyId;
            this.secondDisable = true;
          }
        }
      }
    });
  }

  submitForm() {
    //校验是否能提交
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }

    //附件
    if (this.fileList.length > 0) {
      let files = "";
      this.fileList.forEach(element => {
        files += (element["response"]["data"])+",";
      });
      this.contractBean.fileList = files;
    }else{
      this._notification.create("error", "错误提示", "附件为必填项，请上传附件");
      return false;
    }

    this.contractBean.addUserId = this.userObject.id;
    this.contractBean.roleId = this.userObject.roleId;
    this.contractBean.loggerUserId = JSON.parse(window.localStorage.getItem("user")).id;
    this.isSpinning = true;
    this.httpServcie.addContract(this.contractBean).subscribe(
      data => {
        if (data.status == 200) {
          this.isSpinning = false;
          this._notification.create("success", "成功提示", "新增成功");
          this.outPut.emit(data);
        } else {
          this.isSpinning = false;
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        this.isSpinning = false;
      }
    );
  }

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  executeArray(items, res: any) {
    items.map(item => {
      if (item.checked) {
        res.push({ name: item.text, id: item.value });
      }
      if (item.childList) {
        this.executeArray(item.childList, res);
      }
    });

    return res;
  }

  collapse(array, data, $event) {
    if ($event === false) {
      if (data.childList) {
        data.childList.forEach(d => {
          const target = array.find(a => a.authorId === d.authorId);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [],
      array = [],
      hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.childList) {
        for (let i = node.childList.length - 1; i >= 0; i--) {
          stack.push({
            ...node.childList[i],
            level: node.level + 1,
            expand: false,
            parent: node
          });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.authorId]) {
      hashMap[node.authorId] = true;
      array.push(node);
    }
  }

  //文件上传
  previewImage = "";
  previewVisible = false;
  fileList: UploadFile[] = [];

  //查看
  handlePreview = (file: UploadFile) => {
    this.previewImage =
      this.config.IP +
      this.config.API.getUpload +
      "/" +
      file["response"]["data"] || file.thumbUrl;
    this.previewVisible = true;
  };

  /**
   * 上传就开始调用
   * @param info
   */
  handleChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      this.fileList.forEach(element => {
        element["thumbUrl"] =
          this.config.IP +
          this.config.API.getUpload +
          "/" +
          element["response"]["data"];
      });
      // Get this url from response in real world.
    }
  }

  //移除文件
  nzRemoveFile = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.fileList.length == 1) {
      this.fileList = [];
      return;
    }
    let list: UploadFile[] = [];
    this.fileList.forEach((element, index) => {
      if (element["thumbUrl"] == file.thumbUrl) {
        this.fileList.splice(index, 1);
        this.fileList = this.fileList;
        list = this.fileList;
        this.fileList = [];
      }
    });
    list.forEach(element => {
      this.fileList.push(element);
    });
  };
}
